package cate.game.db.sqlite;

import cate.common.game.trace.GameTraceUtils;
import easy.mysql.map.MyMapper;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

@Slf4j
public abstract class GameSqlite {

    public abstract GameSqlite setup(Object srvId);

    private MyMapper commonMapper = new MyMapper();

    protected void initDao(DataSource ds) {
        try (Connection conn = ds.getConnection()) {
            log.info("SQLite已连接");
            try (Statement s = conn.createStatement()) {
                for(String sql : GameTraceUtils.initSqlAll()) {
                    try {
                        s.execute(sql);
                    } catch (Exception e) {
                        log.error("执行SQLite初始化", e);
                        log.error("获取到的SQL指令: {}", sql);
                    }
                }
            }
        } catch (SQLException e) {
            log.error("", e);
        }
        commonMapper

                .dbType = MyMapper.DB_TYPE_SQLITE;
        commonMapper.setDefaultDS(ds);
    }

    public int insert(Object logEntity) {
        try {
            return commonMapper.insert.one(logEntity);
        } catch (Exception e) {
            log.error("", e);
            return -1;
        }
    }

    public int insert(List logEntityList) {
        if(logEntityList == null || logEntityList.isEmpty()) {
            return 0;
        }
        try {
            return commonMapper.insert.many(logEntityList.get(0).getClass(), logEntityList);
        } catch (Exception e) {
            log.error("", e);
            return -1;
        }
    }

    public int upsert(Object logEntity) {
        try {
            return commonMapper.upsert.one(logEntity);
        } catch (Exception e) {
            log.error("", e);
            return -1;
        }
    }

    public int upsert(List logEntityList) {
        if(logEntityList == null || logEntityList.isEmpty()) {
            return 0;
        }
        try {
            return commonMapper.upsert.many(logEntityList.get(0).getClass(), logEntityList);
        } catch (Exception e) {
            log.error("", e);
            return -1;
        }
    }
}
